#!/usr/bin/env python
# -*- coding: utf-8 -*-

__author__ = 'Michael Liao'

import os, re, time, base64, hashlib, logging

import markdown2

from transwarp.web import get, post, ctx, view, interceptor, seeother, notfound

from apis import *
from models import *
from config import configs

_COOKIE_NAME = 'awesession'
_COOKIE_KEY = configs.session.secret

def _get_page_index():
    page_index = 1
    try:
        page_index = int(ctx.request.get('page', '1'))
    except ValueError:
        pass
    return page_index

def make_signed_cookie(id, password, max_age):
    # build cookie string by: id-expires-md5
    expires = str(int(time.time() + (max_age or 86400)))
    L = [id, expires, hashlib.md5('%s-%s-%s-%s' % (id, password, expires, _COOKIE_KEY)).hexdigest()]
    return '-'.join(L)

def parse_signed_cookie(cookie_str):
    try:
        L = cookie_str.split('-')
        if len(L) != 3:
            return None
        id, expires, md5 = L
        if int(expires) < time.time():
            return None
        user = User.get(id)
        if user is None:
            return None
        if md5 != hashlib.md5('%s-%s-%s-%s' % (id, user.password, expires, _COOKIE_KEY)).hexdigest():
            return None
        return user
    except:
        return None

def check_admin():
    user = ctx.request.user
    if user and user.admin:
        return
    raise APIPermissionError('No permission.')

@interceptor('/')
def user_interceptor(next):
    logging.info('try to bind user from session cookie...')
    user = None
    cookie = ctx.request.cookies.get(_COOKIE_NAME)
    if cookie:
        logging.info('parse session cookie...')
        user = parse_signed_cookie(cookie)
        if user:
            logging.info('bind user <%s> to session...' % user.email)
    ctx.request.user = user
    logging.info('try to bind menus from session cookie...')
    menus = None
    menus = Menu.find_all()
    ctx.request.menus = menus
    return next()

@interceptor('/manage/')
def manage_interceptor(next):
    user = ctx.request.user
    if user and user.admin:
        return next()
    raise seeother('/signin')



@view('index.html')
@get('/')
def index():
    return dict(menus=ctx.request.menus)

@api
@get('/api/menus')
def api_get_menus():
    menus = ctx.request.get('menus', '')
    return dict(menus=menus)

@view('xyfx_index.html')
@get('/xyfx/index')
def xyfx_index():
    menuid = ctx.request.get('menuid', '')
    menus = Menu.find_by('where (parentid=0 or parentid='+menuid + ' )')
    return dict(menus=menus)

@api
@get('/api/xyfx/index')
def api_get_xyfx_index():
    # menus = ctx.request.get('menus', '')
    xyfx_configs = None
    xyfx_configs = Xyfx_config.find_by('order by id desc')
    return dict(xyfx_configs=xyfx_configs)

@view('xyfx_db.html')
@get('/xyfx/db')
def xyfx_db():
    return dict(menus=ctx.request.menus)

@api
@get('/api/xyfx/db')
def api_get_xyfx_db():
    menus = ctx.request.get('menus', '')
    xyfx_configs = None
    xyfx_configs = Xyfx_config.find_by('where type=1 order by id desc')
    xyfx_remotes = Xyfx_remote.find_all()
    return dict(menus=menus, xyfx_configs=xyfx_configs, xyfx_remotes=xyfx_remotes)

@view('xyfx_remote.html')
@get('/xyfx/remote')
def xyfx_remote():
    return dict(menus=ctx.request.menus)

@api
@get('/api/xyfx/remote')
def api_get_xyfx_remote():
    menus = ctx.request.get('menus', '')
    xyfx_remotes = None
    xyfx_remotes = Xyfx_remote.find_by('order by id desc')
    return dict(menus=menus, xyfx_remotes=xyfx_remotes)

@api
@post('/api/xyfx/add_remote_config')
def api_post_xyfx_add_remote():
    menus = ctx.request.get('menus', '')
    i = ctx.request.input()
    serverip = i.serverip.strip()
    username = i.username.strip().lower()
    password = i.password.strip()
    port = i.port.strip().lower()
    id = Xyfx_remote.count_all() + 1
    xr = Xyfx_remote(serverip=serverip, username=username, \
        password=password, port=port, id=id)
    xr.insert()
    return dict(menus=menus)

@api
@post('/api/xyfx/add_db_config')
def api_post_xyfx_add_db():
    menus = ctx.request.get('menus', '')
    i = ctx.request.input()
    configid = Xyfx_config.count_all() + 1
    serverip = i.serverip.strip()
    username = i.username.strip().lower()
    password = i.password.strip()
    dbname = i.dbname.strip().lower()
    id = Xyfx_db_config.count_all() + 1
    xdc = Xyfx_db_config(serverip=serverip, username=username, \
        password=password, dbname=dbname, configid=configid, id=id)
    xdc.insert()

    ###
    xcid = configid
    xcname = serverip + '_' + username
    xctype = 1
    xcfilename = 'oradb.conf'
    xcpath  = '/xyfx/etc/oradb.conf'
    xccommets   = 'auto create oradb.conf'
    xc = Xyfx_config(id=xcid, name=xcname, type=xctype, filename=xcfilename, path=xcpath, comments=xccommets)
    xc.insert()
    return dict(menus=menus)

@api
@post('/api/configs/:config_id/edit')
def api_post_xyfx_config_add(config_id):
    menus = ctx.request.get('menus', '')
    return dict(menus=menus)

@api
@post('/api/configs/:config_id/delete')
def api_post_xyfx_config_delete(config_id):
    print '###############'
    xc = Xyfx_config.get(config_id)
    xc.delete()
    print '###############'
    return dict()
@api
@get('/api/configs/:config_id/show_remotes')
def api_get_xyfx_remote_show(config_id):
    show_remotes = Xyfx_remote.find_all()
    print show_remotes
    return dict(show_remotes=show_remotes)

@api
@post('/api/configs/upload_to_servers')
def api_post_xyfx_upload_to_servers () :
    menus = ctx.request.get('menus', '')
    i = ctx.request.input()
    config = i.show_config_id
    checked = i.checkedServers
    print '###############'
    print config
    print checked

    print '###############'
    return dict(menus=menus)
    

#################################################################

@view('ljt_index.html')
@get('/ljt/index')
def ljt_index():
    menuid = ctx.request.get('menuid', '')
    menus = Menu.find_by('where (parentid=0 or parentid='+menuid + ' )')
    return dict(menus=menus)

@api
@get('/api/ljt/index')
def api_get_ljt_index():
    ljt_taskinfo = None
    ljt_taskinfo = Ljt_taskinfo.find_by('order by id desc')
    
    return dict(ljt_taskinfo=ljt_taskinfo)


@api
@post('/api/ljt/upload')
def api_post_ljt_upload () :
    menus = ctx.request.get('menus', '')
    #files = request.FILES.getlist('files[]')
    files = ctx.request.get('files[]', '')
    print files.file
    print files.filename
    print ctx.request._get_raw_input()
    content = files.file.read()
    # print content
    destination = './tmp/'
    # destination.write(content)
    if not os.path.exists(destination):
        os.makedirs(destination)
    with open(destination+files.filename, 'wb+') as d:
        d.write(content)
    return dict(menus=menus)